import React, { PureComponent } from 'react';
// 引入框架
import { Input, Button, message } from 'antd'
// 发送axios
import Axios from 'axios';
// 引入接口
import { webSite } from '../website'
// 引入框架ico
import { LeftCircleFilled, ManOutlined, WomanOutlined } from '@ant-design/icons';
// 引入样式
import './scss/reg.scss'
export default class Register extends PureComponent {
  constructor() {
    super()
    this.state = {
      // 账号框
      username: '',
      // 密码框
      password: '',
      // 确认密码
      ConfirmPassword: '',
      // 邮箱
      QQEmail: '',
      // 验证码
      code: '',
      // 获取验证码
      getCode: '获取验证码',
      // 获取验证码是否为可选中状态
      disabled: true,
      // 验证码是否正确的解释
      testCode: '',
      // 错误阻止提交
      CodeFals: false
    }
  }
  // 清除订阅者
  componentWillUnmount () {
    // 卸载异步操作设置状态
    this.setState = () => {
      return;
    }
  }
  // input的输入事件
  handleInput = ({ target }) => {
    let { name, value } = target
    // 设置input和state同步
    this.setState({
      [name]: value
    })
  }
  // 获取验证码
  formCode = () => {
    const _this = this;
    // 正则表达式
    let email = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
    if (this.state.QQEmail === '') {
      message.error({ content: '邮箱未输入！！！', className: 'bulletChatMessage' });
      return;
    } else if (!email.test(this.state.QQEmail)) {
      message.error({ content: '邮箱格式错误！！！', className: 'bulletChatMessage' })
      return;
    }
    // 判断邮箱是否被注册
    let isEmail = this.state.QQEmail;
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/rightIsEmail",
      {
        email: isEmail
      })
      .then(err => {
        if (err.data.code === 'C0006') {
          message.error({ content: '邮箱已被注册', className: 'bulletChatMessage' });
          this.setState({
            // 清空邮箱地址
            QQEmail: ''
          })
          return;
        } else if (err.data.code === 'C0007') {
          // 发送请求
          const AxiosLogin = Axios.create({
            baseURL: `${webSite}:3003`
          });
          // 登录的api请求
          const setApiLogin = () => {
            // 把用户的建议和联系方式发送到后台
            return AxiosLogin.post("/QQEmail", { QQEmail: this.state.QQEmail });
          }

          setApiLogin().then(err => {
            // 数据获取成功之后禁止输入框
            if (err.data.code === 'B0001') {
              // 获取验证码成功之后改变状态
              _this.setState({
                disabled: !_this.state.disabled
              })
              // 使用定时器禁止用户连续点击
              let item = 60;
              let timeId = setInterval(function () {
                item--;
                _this.setState({
                  getCode: item + '秒后重新获取'
                })
                if (item < 1) {
                  window.clearInterval(timeId)
                  _this.setState({
                    disabled: !_this.state.disabled,
                    getCode: '获取验证码'
                  })
                }
              }, 1000)
            }
          })
        }
      }).catch(() => {
        message.error({ content: '网络错误', className: 'bulletChatMessage' });
      })
  }
  // 注册按钮的点击事件
  formBtn = (sex) => {
    let username = this.state.username.replace(/\s+/g, "");
    let password = this.state.password.replace(/\s+/g, "");
    let ConfirmPassword = this.state.ConfirmPassword.replace(/\s+/g, "");
    let QQEmail = this.state.QQEmail.replace(/\s+/g, "");
    let code = this.state.code.replace(/\s+/g, "");
    // 判断用户是否输入空格
    if (username === '') {
      message.error({ content: '请输入账号！！！', className: 'bulletChatMessage' });
      return;
    } else if (username.length < 6) {
      message.error({ content: '账号不能少于6位', className: 'bulletChatMessage' });
      return;
    } else if (password === '') {
      message.error({ content: '设置密码！！！', className: 'bulletChatMessage' });
      return;
    } else if (password !== ConfirmPassword) {
      message.error({ content: '两次密码输入不一致！！！', className: 'bulletChatMessage' });
      return;
    } else if (QQEmail === '') {
      message.error({ content: '邮箱未输入！！！', className: 'bulletChatMessage' });
      return;
    } else if (code === '') {
      message.error({ content: '验证码未输入！！！', className: 'bulletChatMessage' });
      return;
    }
    // 判断用户输入的是否是汉字
    let setH = /[\u4E00-\u9FA5]/g;
    // 判断不能有汉字
    if (setH.test(username) || setH.test(password) || setH.test(ConfirmPassword) || setH.test(QQEmail) || setH.test(code)) {
      message.error({ content: '输入的内容不能出现汉字！！！', className: 'bulletChatMessage' });
      return;
    }
    // 判断账号紧支持数字
    if (!/^[0-9]+$/.test(username)) {
      message.error({ content: '用户名只支持数字', className: 'bulletChatMessage' })
      return;
    }
    // 判断邮箱格式
    let email = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
    if (!email.test(this.state.QQEmail)) {
      message.error({ content: '邮箱格式错误！！！', className: 'bulletChatMessage' })
      return;
    }
    // 把数字上传到服务器
    // 发送注册数据到后台
    // 判断验证码是否正确
    if (!this.state.CodeFals) {
      message.error({ content: '请输入正确的验证码！！！', className: 'bulletChatMessage' })
      return;
    }
    // 用户名或邮箱错误禁止提交

    // 如果用户名和邮箱没有问题就添加到服务器
    const AxiosLogin = Axios.create({
      baseURL: `${webSite}:3003`
    });

    // 登录的api请求
    const setApiLogin = () => {
      // 把用户的建议和联系方式发送到后台
      return AxiosLogin.post("/right", {
        user: this.state.username,
        password: this.state.password,
        email: this.state.QQEmail,
        sex: sex
      });
    }

    setApiLogin().then(err => {
      if (err.data.code === 'C0003') {
        message.success({ content: '创建账号成功', className: 'bulletChatMessage' });
        // 跳转到注册页
        this.props.history.replace('/login')
      }
    }).catch(() => {
      message.error({ content: '网络错误', className: 'bulletChatMessage' });
    })
  }
  // 注册按钮
  RegBtn = () => {
    // 跳转到登录页
    this.props.history.replace('/login')
  }
  // 验证码的判断
  CodeInput = ({ target }) => {
    let { name, value } = target
    // 设置input和state同步
    this.setState({
      [name]: value
    })
    // 发送请求进行判断
    // 发送请求
    if (value.length === 5) {
      const AxiosLogin = Axios.create({
        baseURL: `${webSite}:3003`
      });

      // 登录的api请求
      const setApiLogin = () => {
        // 把用户的建议和联系方式发送到后台
        return AxiosLogin.post("/setEmail", { isCode: value });
      }

      setApiLogin().then(err => {
        if (err.data.code === 'B0003') {
          this.setState({
            testCode: err.data.msg,
            CodeFals: false
          })
          return;
        }
        // 验证码输入正确
        this.setState({
          testCode: '',
          CodeFals: true
        })
      }).catch(() => {
        message.error({ content: '网络错误', className: 'bulletChatMessage' });
      })
    }
  }
  // 输入框脱离焦点事件
  BlueIndex = () => {
    let username = this.state.username;
    // 判断不能是中文
    if (/[\u4E00-\u9FA5]/g.test(username)) {
      message.error({ content: '输入框不能使用汉字！！！', className: 'bulletChatMessage' });
      return;
    }
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/rightIsUseerName", { user: username }).then(err => {
      if (err.data.code === 'C0005') {
        message.error({ content: '用户名已被注册！！！', className: 'bulletChatMessage' });
        this.setState({
          username: ''
        })
      }
    }).catch(() => {
      message.error({ content: '网络错误', className: 'bulletChatMessage' });
    })
  }
  // 渲染页面
  render () {
    return (
      <div className='register'>
        {/* 顶部logo */}
        <div className='login_logo'>
          <img src={require('./img/rigister.jpg')} alt="登录的logo" />
          <div>
            <h2>注册</h2>
            <p>花开彼岸天</p>
          </div>
        </div>
        {/* 登录框 */}
        <div className='right_div'>
          {/* 输入框 */}
          <Input placeholder="账号" className='username_right' value={this.state.username} name='username' onChange={this.handleInput} autoComplete="off" onBlur={this.BlueIndex} />
          {/* 密码 */}
          <Input placeholder="密码" className='username_right' value={this.state.password} name='password' onChange={this.handleInput} autoComplete="off" />
          {/* 确认密码 */}
          <Input placeholder="重复密码" className='username_right' value={this.state.ConfirmPassword} name='ConfirmPassword' onChange={this.handleInput} autoComplete="off" />
          {/* 邮箱 */}
          <Input placeholder="邮箱" className='username_right' value={this.state.QQEmail} name='QQEmail' onChange={this.handleInput} autoComplete="off" />
          {/* 验证码 */}
          <Input placeholder="验证码" className='username_right code_btn_reg' value={this.state.Confirmcode} name='code' onChange={this.CodeInput} autoComplete="off" maxLength='5' />
          <Button type="primary" block onClick={this.formCode} className='btn_Code' disabled={!this.state.disabled}>{this.state.getCode}</Button>
          {/* 验证吗是否正确 */}
          <p style={{ color: 'red' }}>{this.state.testCode}</p>
        </div>
        {/* 提交按钮 */}
        <div className='btn_register_from'>
          <LeftCircleFilled onClick={this.RegBtn} className='reg_Go_reg' />
          <div className='reg_from'>
            <div className='reg_back_boy'>
              <ManOutlined className='reg_boy' onClick={() => this.formBtn('1')} />
            </div>
            <div className='reg_back_boy' style={{ background: 'rgb(249,187,208)' }}>
              <WomanOutlined className='reg_female' onClick={() => this.formBtn('2')} />
            </div>
          </div>
        </div>
      </div >
    )
  }
}